package cn.waka.sys.admin.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.waka.sys.admin.dao.IUserDao;
import cn.waka.sys.admin.object.Page;
import cn.waka.sys.admin.object.User;

@Service
public class UserService {

	
	private IUserDao userDao;

	@Autowired
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
	
	
	public User checkUser(String login,String password){
		if(login==null||password==null){
			return null;
		}
		User u=userDao.findByLogin(login);
		if(u!=null){
			String password1 = DigestUtils.md5DigestAsHex(password.toString().getBytes()).toLowerCase();
			String password0=u.getPassword();
			if(password0.equals(password1)){
				return u;
			}
			
		}
		return null;
	}
	
	
	public Page findPage(Page p,Map<String,String> param){
		int page=p.getPage();
		int start=(page-1)*p.getSize();
		List<User> list=userDao.findList(param,start,p.getSize());
		int count=userDao.findCount(param);
		p.setData(list);
		p.setCount(count);
		int totalCount=1;
		if(count%p.getSize()>0){
			totalCount=(int) Math.floor(count/p.getSize());
			totalCount++;
		}else{
			totalCount=count/p.getSize();
		}
		p.setTotalPage(totalCount);
		return p;
	}

	public User findById(int uid){
		return userDao.findById(uid);
	}

	public int saveUser(User u){
		int rs = 1;
		if(u.getId()>0){
			rs = userDao.updateUser(u);
		}else{
			rs = userDao.insert(u);
		}
		return rs;
	}
	
	
	public boolean updatePassword(int uid,String password){
		return userDao.updatePassword(uid, password)>0;
	}

	public int saveAuth(int uid,String auth){
		return userDao.saveAuth(uid,auth);
	}
	
	public int updateStatus(int uid,String status){
		return userDao.updateStatus(uid,status);
	}
	
	public int del(int uid){
		return userDao.del(uid);
	}
	
}
